package com.shouxin.attendance.serialport;

import com.shouxin.attendance.constants.PrefKey;
import com.shouxin.attendance.utils.SharedPref;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 数据发送辅助类
 * Created by ligang on 16/7/27.
 */
public final class SendHelper {

	private static final Logger logger = Logger.getLogger(SendHelper.class);

	private HashMap<String, ClearTask> taskHashMap = new HashMap<>();

	private Timer timer = new Timer();

	private SendHelper() {
	}

	public static SendHelper getInstance() {
		return Instance.instance;
	}

	public void sendAlarmOpenCmd(String port) {
		boolean trailSwitch = SharedPref.getBoolean(PrefKey.TRAIL_SWITCH, true);
		if (!trailSwitch) {
			logger.debug(port + "--" + "开始发送告警指令...");
			String cmd = AlarmCMD.getOpenCmd(port);
			SerialManager.getInstance().sendCmds(cmd);
		} else {
			logger.debug("当前处于试用阶段");
			String cmd = AlarmCMD.getOpenCmd(port);
			SerialManager.getInstance().sendCmds(cmd);
			// 2秒内自动取消告警
			ClearTask task = taskHashMap.get(port);
			if (task != null) {
				task.cancel();
			}
			task = new ClearTask(port);
			taskHashMap.put(port, task);
			timer.schedule(task, 1000);
		}
		/*int alarmNum = SharedPref.getInt(PrefKey.ALARM_NUMBER_COUNT, 0);
		SharedPref.putInt(PrefKey.ALARM_NUMBER_COUNT, ++alarmNum);
		EventBus.getDefault().post(new EventAlarmCount(alarmNum));*/
	}

	public void sendAlarmCloseCmd(String port) {
		logger.debug(port + "--" + "开始发送消警指令...");
		String cmd = AlarmCMD.getCloseCmd(port);
		SerialManager.getInstance().sendCmds(cmd);
	}

	private static class Instance {

		static SendHelper instance = new SendHelper();
	}

	private class ClearTask extends TimerTask {

		private String port;

		ClearTask(String port) {
			this.port = port;
		}

		@Override
		public void run() {
			logger.debug("2秒发送消警指令...");
			sendAlarmCloseCmd(port);
		}
	}
}
